<?php
namespace app\admin\model;

use think\Model;
use think\Db;
use think\facade\Config;

class Models extends Model
{
    protected $ext_table = '_data';
    protected $insert = ['status' => 1];
    
    public function addModel($data)
    {
        if (empty($data)) {
            return false;
        }
        //创建模型表和模型附表
        if ($this->createTable($data)) {
            $id = $this->insertGetId($data);
            if ($id) {
                $this->creatField($id);
            }
            return true;
        }
        return false;
    }
	
	public function editModel($data){
		if (empty($data)) {
		    return false;
		}
		$this->update($data);
		return true;
	}
    
    public function creatField($id)
    {
        $data = [
            [
                'ename'=>"title",
                'model_id' =>$id,
                'cname'=>"标题",
                'type'=>"20",
                'descript'=>"标题",
                'sort'=>"1",
                'validate'=>"1",
				'value'=>'',
				'show'=>"1",
				'addendum'=>1,
				'isedit' =>2
                
            ],[
                'ename'=>"titlecolor",
                'model_id' =>$id,
                'cname'=>"标题颜色",
                'type'=>"1",
                'descript'=>"标题颜色",
                'sort'=>"2",
                'validate'=>"2",
				'value'=>'',
                'show'=>"2",
				'addendum'=>1,
				'isedit' =>2
            ],[
                'ename'=>"keywords",
                'model_id' =>$id,
                'cname'=>"关键词",
                'type'=>"1",
                'descript'=>"关键词",
                'sort'=>"3",
                'validate'=>"2",
				'value'=>'',
                'show'=>"1",
				'addendum'=>1,
				'isedit' =>2
            ],[
                'ename'=>"description",
                'model_id' =>$id,
                'cname'=>"描述",
                'type'=>"3",
                'descript'=>"描述",
                'sort'=>"4",
                'validate'=>"2",
				'value'=>'',
                'show'=>"1",
				'addendum'=>1,
				'isedit' =>2
            ],[
                'ename'=>"author",
                'model_id' =>$id,
                'cname'=>"来源",
                'type'=>"1",
                'descript'=>"来源",
                'sort'=>"5",
                'validate'=>"2",
				'value'=>'',
                'show'=>"1",
				'addendum'=>1,
				'isedit' =>2
            ],[
                'ename'=>"click",
                'model_id' =>$id,
                'cname'=>"点击数",
                'type'=>"9",
                'descript'=>"点击数",
                'sort'=>"6",
                'validate'=>"2",
				'value'=>'',
                'show'=>"1",
				'addendum'=>1,
				'isedit' =>2
            ],[
                'ename'=>"thumb",
                'model_id' =>$id,
                'cname'=>"缩略图",
                'type'=>"8",
                'descript'=>"缩略图",
                'sort'=>"7",
                'validate'=>"2",
				'value'=>'',
                'show'=>"1",
				'addendum'=>1,
				'isedit' =>2
            ],[
                'ename'=>"inputtime",
                'model_id' =>$id,
                'cname'=>"输入时间",
                'type'=>"10",
                'descript'=>"输入时间",
                'sort'=>"8",
                'validate'=>"2",
				'value'=>'',
                'show'=>"1",
				'addendum'=>1,
				'isedit' =>2
            ],[
                'ename'=>"updatetime",
                'model_id' =>$id,
                'cname'=>"更新时间",
                'type'=>"10",
                'descript'=>"更新时间",
                'sort'=>"9",
                'validate'=>"2",
				'value'=>'',
                'show'=>"1",
				'addendum'=>1,
				'isedit' =>2
            ],[
                'ename'=>"status",
                'model_id' =>$id,
                'cname'=>"状态",
                'type'=>"4",
                'descript'=>"状态",
                'sort'=>"10",
                'validate'=>"2",
				'value'=>'开启,1|关闭,0',
                'show'=>"2",
				'addendum'=>1,
				'isedit' =>2
            ],[
                'ename'=>"istop",
                'model_id' =>$id,
                'cname'=>"是否置顶",
                'type'=>"4",
                'descript'=>"是否置顶",
                'sort'=>"11",
                'validate'=>"2",
				'value'=>'开启,1|关闭,0',
                'show'=>"1",
				'addendum'=>1,
				'isedit' =>2
            ],[
                'ename'=>"sort",
                'model_id' =>$id,
                'cname'=>"排序",
                'type'=>"9",
                'descript'=>"排序",
                'sort'=>"12",
                'validate'=>"2",
				'value'=>'',
				'show'=>"1",
				'addendum'=>1,
				'isedit' =>2
            ],[
                'ename'=>"show",
                'model_id' =>$id,
                'cname'=>"是否显示",
                'type'=>"4",
                'descript'=>"是否显示",
                'sort'=>"13",
                'validate'=>"2",
				'value'=>'开启,1|关闭,0',
				'show'=>"1",
				'addendum'=>1,
				'isedit' =>2
                
            ],[
                'ename'=>"cid",
                'model_id' =>$id,
                'cname'=>"栏目id",
                'type'=>"9",
                'descript'=>"栏目id",
                'sort'=>"14",
                'validate'=>"2",
				'value'=>'',
                'show'=>"2",
				'addendum'=>1,
				'isedit' =>2
            ],[
                'ename'=>"tag_id",
                'model_id' =>$id,
                'cname'=>"标签",
                'type'=>"2",
                'descript'=>"标签",
                'sort'=>"15",
                'validate'=>"2",
				'value'=>'头条,1|推荐,2|置顶,3',
                'show'=>"1",
				'addendum'=>1,
				'isedit' =>2
            ],[
			    'ename'=>"content",
			    'model_id' =>$id,
			    'cname'=>"内容",
			    'type'=>"11",
			    'descript'=>"内容",
			    'sort'=>"15",
			    'validate'=>"2",
				'value'=>'',
			    'show'=>"1",
				'addendum'=>2,
				'isedit' =>2
			]
        ];
        Db::name('models_field')->insertAll($data);
        return true;
    }
    
    /**
     * 创建内容模型
     */
    protected function createTable($data)
    {
        $data['table_name'] = strtolower($data['table_name']);
        $table = Config::get("database.prefix") . $data['table_name'];
        if ($this->table_exists($data['table_name'])) {
            $this->error = '创建失败！' . $table . '表已经存在~';
            return false;
        }
        $sql = <<<EOF
				CREATE TABLE `{$table}` (
				`aid` int(10) UNSIGNED NOT NULL AUTO_INCREMENT COMMENT '文章id',
				`title` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '标题',
				`titlecolor` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '标题颜色',
				`keywords` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '关键字',
				`description` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '描述',
				`author` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '作者',
				`click` int(10) NULL DEFAULT NULL COMMENT '点击数',
				`thumb` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '缩略图',
				`pics`  text COLLATE utf8_unicode_ci COMMENT '图集',
				`did` int(11) NULL DEFAULT NULL COMMENT '内容id',
				`inputtime` char(10) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '创建时间',
				`updatetime` char(10) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '更新时间',
				`status` tinyint(1) NULL DEFAULT NULL COMMENT '是否删除(1:正常,0:已删除)',
				`istop` tinyint(1) NULL DEFAULT NULL COMMENT '是否置顶(1:置顶,0:不置顶)',
				`sort` int(11) UNSIGNED NULL DEFAULT NULL COMMENT '排序',
				`show` tinyint(1) NULL DEFAULT NULL COMMENT '是否显示(1:显示,0:不显示)',
				`cid` int(11) NULL DEFAULT NULL COMMENT '对应栏目id',
				`tag_id` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '标签',
				PRIMARY KEY (`aid`) USING BTREE
				) ENGINE = MyISAM AUTO_INCREMENT = 10 CHARACTER SET = utf8 COLLATE = utf8_general_ci COMMENT = '{$data['name']}模型表' ROW_FORMAT = Dynamic;
EOF;
        try {
            $res = Db::execute($sql);
        } catch (\Exception $e) {
            $this->error = $e->getMessage();
            return false;
        }
        // 新建附属表
        $sql = <<<EOF
			CREATE TABLE `{$table}{$this->ext_table}` (
			`id` int(10) UNSIGNED NOT NULL AUTO_INCREMENT COMMENT '主键id',
			`content` text COLLATE utf8_unicode_ci COMMENT '内容',
			PRIMARY KEY (`id`)
			) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='{$data['name']}模型表';
EOF;
        try {
            $res = Db::execute($sql);
        } catch (\Exception $e) {
            $this->error = $e->getMessage();
            return false;
        }
        return true;
    }
    
	public function delModel($data)
	{
	    if (empty($data['id'])) {
	        return false;
	    }
	    //表名
	    $model_table = $data['table_name'];
	    //删除模型数据
	    self::destroy($data['id']);
	    //删除所有和这个模型相关的字段
	    Db::name("modelsField")->where(array("model_id" =>$data['id']))->delete();
	    //删除主表和附表
	    $this->deleteTable($model_table);
	    $this->deleteTable($model_table . "_data");
	    return true;
	}
	
    /**
     * 检查表是否存在
     * $table 不带表前缀
     */
    public function table_exists($table)
    {
        $table = Config::get("database.prefix") . strtolower($table);
        if (true == Db::query("SHOW TABLES LIKE '{$table}'")) {
            return true;
        } else {
            return false;
        }
    }
	
	/**
	 * 删除表
	 * $table 不带表前缀
	 */
	public function deleteTable($table)
	{
	    if ($this->table_exists($table)) {
	        $this->drop_table($table);
	    }
	    return true;
	}
	/**
	 * 删除表
	 * @param string $tablename 不带表前缀的表名
	 * @return type
	 */
	public function drop_table($table)
	{
	    $table = Config::get("database.prefix") . strtolower($table);
	    return Db::query("DROP TABLE $table");
	}
}
